package com.davidlife.controller;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.URLEncoder;
import java.util.List;
import java.util.UUID;

@Controller
public class FileUploadController {
    //传统方式上传文件
    @RequestMapping(value = "fileupload1", method = RequestMethod.POST)
    public String fileupload1(HttpServletRequest request) throws Exception {
        System.out.println("传统方式文件上传......");

        //使用fileupload组件完成文件上传
        //上传的位置
        String path = request.getSession().getServletContext().getRealPath("uploads");
        System.out.println(path);

        //判断，该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
            //创建该文件夹
            file.mkdirs();
        }

        //解析request对象，获取上传文件项
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        //解析request
        List<FileItem> items = upload.parseRequest(request);
        //遍历
        for (FileItem item : items) {
            //进行判断，当前item对象是否是上传文件项
            if (item.isFormField()) {
                //说明是普通表单
            } else {
                //说明是上传文件项
                //获取上传文件的名称
                String filename = item.getName();
                //把文件的名称设置为唯一值，uuid
                String uuid = UUID.randomUUID().toString().replace("-", "");
                filename = uuid + "_" + filename;
                //完成上传文件
                item.write(new File(path, filename));
                //删除临时文件
                item.delete();
            }
        }
        return "success";
    }

    //SpringMVC方式上传文件
    @RequestMapping(value = "fileupload2", method = RequestMethod.POST)
    //这里注意参数名uploadfile要与上传表单中<input type="file" name="uploadfile"/><br/>的name一致
    public String fileupload2(HttpServletRequest request, MultipartFile uploadfile, String username) throws Exception {
        System.out.println("springmvc文件上传...");

        System.out.println("其他表单项也接受到了，username：" + username);
        // 上传的位置
        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        System.out.println(path);
        // 判断，该路径是否存在
        File file = new File(path);
        if (!file.exists()) {
            // 创建该文件夹
            file.mkdirs();
        }

        // 获取上传文件的名称
        String filename = uploadfile.getOriginalFilename();
        // 把文件的名称设置唯一值，uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid + "_" + filename;
        // 完成文件上传
        uploadfile.transferTo(new File(path, filename));

        return "success";
    }

    //实现SpringMVC跨服务器方式文件上传
    //1. 导入开发需要的jar包
    /*
    <dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.18.1</version>
    </dependency>
    <dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.18.1</version>
    </dependency>
     */

    /**
     * 注意：要配置使file upload server具有可写的权限，才能上传成功，否则报403的错误，在web.xml(tomcat/conf或项目下的web.xml配均可)中配置：
     *             ```
     *             <servlet>
     *                 <servlet-name>default</servlet-name>
     *                 <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
     *                 <init-param>
     *                     <param-name>debug</param-name>
     *                     <param-value>0</param-value>
     *                 </init-param>
     *                 <init-param>
     *                     <param-name>readonly</param-name>
     *                     <param-value>false</param-value>
     *                 </init-param>
     *                 <init-param>
     *                     <param-name>listings</param-name>
     *                     <param-value>false</param-value>
     *                 </init-param>
     *                 <load-on-startup>1</load-on-startup>
     *             </servlet>
     *             ```
     */
    //SpringMVC跨服务器方式的文件上传
    @RequestMapping(value = "/fileupload3")
    public String fileupload3(MultipartFile upload) throws Exception {
        System.out.println("SpringMVC跨服务器方式的文件上传...");
        // 定义图片服务器的请求路径
        String path = "http://localhost:9090/fileuploadserver/uploads/";
        // 获取到上传文件的名称
        String filename = upload.getOriginalFilename();
        //这里注意上传文件中若有中文，会报http 400的错误，可以把文件名使用URL Encode解决
        filename = URLEncoder.encode(filename, "UTF-8");
        String uuid = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        // 把文件的名称唯一化
        filename = uuid + "_" + filename;
        // 向图片服务器上传文件
        // 创建客户端对象
        Client client = Client.create();
        // 连接图片服务器
        WebResource webResource = client.resource(path + filename);
        // 上传文件
        webResource.put(upload.getBytes());
        return "success";
    }
}
